from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from typing import Optional
import logging

from ..core.database import get_db
from ..core.security import decode_token
from ..models.user import User

security = HTTPBearer(auto_error=False)
logger = logging.getLogger(__name__)


def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db)
) -> User:
    """获取当前登录用户"""
    logger.info(f"[认证] credentials对象: {credentials}")
    logger.info(f"[认证] credentials是否为None: {credentials is None}")
    
    if credentials is None:
        logger.error("[认证] 没有提供认证凭证")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="需要认证",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    token = credentials.credentials
    logger.info(f"[认证] 收到的Token完整内容: {token}")
    logger.info(f"[认证] Token长度: {len(token)}")
    logger.info(f"[认证] Token前30字符: {token[:30]}...")
    
    payload = decode_token(token)
    logger.info(f"[认证] 解码payload: {payload}")
    
    if payload is None:
        logger.error("[认证] Token解码失败")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的认证凭证",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    token_type = payload.get("type")
    if token_type != "access":
        logger.error(f"[认证] 错误的token类型: {token_type}")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的令牌类型",
        )
    
    user_id: Optional[int] = payload.get("sub")
    logger.info(f"[认证] 从payload获取的sub: {user_id}, 类型: {type(user_id)}")
    
    # 如果 sub 是字符串，转换为整数
    if isinstance(user_id, str):
        try:
            user_id = int(user_id)
            logger.info(f"[认证] 已转换为整数: {user_id}")
        except ValueError:
            logger.error(f"[认证] 无法将sub转换为整数: {user_id}")
            user_id = None
    
    if user_id is None:
        logger.error("[认证] Token中没有有效的用户ID")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的令牌载荷",
        )
    
    user = db.query(User).filter(User.id == user_id).first()
    if user is None:
        logger.error(f"[认证] 找不到用户ID: {user_id}")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户不存在",
        )
    
    logger.info(f"[认证] 成功认证用户: {user.username}")
    return user

